package main

import (
	"fmt"
	"github.com/hyperledger/fabric/core/chaincode/shim"
	pb "github.com/hyperledger/fabric/protos/peer"
)

type Helloworld struct {
}

/**



    peer chaincode install -n helloworld_1222 -v 1.0 -p gitee.com/robertrfeng/fabric_cc_study/binny



	系统初始化方法， 在部署chaincode的过程中当执行命令

    peer chaincode instantiate -o orderer.qklszzn.com:7050 -C mytestchannel -n helloworld_1222 -v 1.0 -c '{"Args":["init","a","100","b","200"]}' -P "OR ('Org1MSP.member','Org2MSP.member')"


    的时候会调用该方法


	https://github.com/hyperledger/fabric/blob/release/core/chaincode/shim/interfaces.go  所有的注释这里

*/
func (t *Helloworld) Init(stub shim.ChaincodeStubInterface) pb.Response {
	fmt.Println(" <<  ========  success init it is view in docker  ==========  >> ")
	return shim.Success([]byte("success init "))
}



/**

  主业务逻辑，执行命令
  peer chaincode invoke -o 192.168.35.131:7050 -C roberttestchannel -n r_test_cc6 -c '{"Args":["invoke","aa","ss","100"]}'

  的时候系统会调用该方法并传入相关的参数，注意 "invoke" 之后的参数是需要传入的参数



*/
func (t *Helloworld) Invoke(stub shim.ChaincodeStubInterface) pb.Response {

	function, args := stub.GetFunctionAndParameters()

	var a_parm = args[0]
	var b_parm = args[1]
	var c_parm = args[2]

	fmt.Println("  ========  curr method is big invoke   ========== ")
	fmt.Printf(" parm is  %s  %s  %s  %s  \n ", a_parm, b_parm, c_parm, function)

	if function == "get" {
		return t.get(stub, args)
	} else if function == "set" {
		return t.set(stub, args)
	}

	return shim.Error("Invalid invoke function name. Expecting \"invoke\" \"query\"")
}
// test get method
/**

调用方法

peer chaincode invoke -o orderer.qklszzn.com:7050  --waitForEvent -C mytestchannel -n helloworld_1222  -c '{"Args":["set","get","冬至已至","fabric--2019-12-22"]}'


调用方法

peer chaincode query -C mytestchannel -n helloworld_1222 -c '{"Args":["get","get","key1222","chaincode v 1.5 = query11111"]}'

*/
func (t *Helloworld) set(stub shim.ChaincodeStubInterface, args []string) pb.Response {
	err := stub.PutState(args[0], []byte(args[1]))
	if err != nil {
		return shim.Error(err.Error())
	}
	return shim.Success(nil)
}

func (t *Helloworld) get(stub shim.ChaincodeStubInterface, args [] string) pb.Response {

	value, err := stub.GetState(args[0])

	if err != nil {
		return shim.Error(err.Error())
	}

	return shim.Success(value)
}

func main() {
	err := shim.Start(new(Helloworld))
	if err != nil {
		fmt.Println("start error")
	}
}
